package com.web.cms.doc.service;

import com.blue.core.dict.UploadType;
import com.blue.jdbc.JdbcDataSource;
import com.blue.jdbc.Page;
import com.web.cms.doc.dao.DocDao;
import com.web.cms.doc.dao.DocFileDao;
import com.web.cms.doc.dao.WebDao;
import com.web.cms.doc.model.DocFile;
import com.web.core.util.Const;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service("cmsDocFileService")
@Transactional
@JdbcDataSource(Const.DS_CMS)
public class DocFileService
{
	@Autowired
	private DocFileDao docFileDao;
	@Autowired
	private DocDao docDao;
	@Autowired
	private WebDao webDao;
	
	public DocFileService()
	{
	}
	
	public DocFile add(DocFile file)
	{
		file.setType(UploadType.getType(file.getMimeType(), file.getName()));
		docFileDao.save(file);
		webDao.inc(file.getWebId(), "files", 1, "fileSize", file.getSize());
		
		DocFile f = docFileDao.getSelect(file.getId());
		return f;
	}
	
	public List<DocFile> list(DocFile file)
	{
		List<DocFile> list = docFileDao.list(file);
		return list;
	}
	
	public Page<DocFile> list(DocFile file, Page<DocFile> page)
	{
		page = docFileDao.list(file, page);
		return page;
	}
	
	public void delete(DocFile file)
	{
		file = docFileDao.get(file.getId());
		if (file == null)
			return;
		
		docFileDao.delete(file);
		
		webDao.inc(file.getWebId(), "files", -1, "fileSize", -file.getSize());
		
		if (file.getDocId() != null)
		{
			docDao.inc(file.getDocId(), "files", -1, "fileSize", -file.getSize());
		}
	}
	
}
